package friot.service.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import friot.model.user.dtos.UserLoginDto;
import friot.model.user.entity.CloudUser;
import friot.service.user.mapper.UserMapper;
import friot.service.user.service.UserService;
import friot.utils.constants.AppHttpCodeEnum;
import friot.utils.exception.ServiceException;
import friot.utils.tools.JwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2023-11-24 16:22:18
 */
@Service("cloudUserService")
public class UserServiceImpl extends ServiceImpl<UserMapper, CloudUser> implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 注册用户
     *
     * @param dto 注册信息
     */
    @Override
    public void registerCount(UserLoginDto dto) {
        // 非空判断
        if (dto.getName() == null || dto.getEmail() == null || dto.getPassword() == null) {
            throw new ServiceException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 检测邮箱是否已注册
        boolean exists = userMapper.exists(Wrappers.lambdaQuery(CloudUser.class).eq(CloudUser::getEmail, dto.getEmail()));
        if (exists) {
            throw new ServiceException(AppHttpCodeEnum.DATA_EXIST);
        }

        // 注册账号
        CloudUser user = new CloudUser();
        user.setName(dto.getName());
        user.setEmail(dto.getEmail());
        String salt = RandomUtil.randomString(10);
        user.setSalt(salt);
        user.setPassword(DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes()));
        userMapper.insert(user);
    }

    /**
     * 用户登录
     *
     * @param dto 登录信息
     */
    @Override
    public String login(UserLoginDto dto) {
        // 参数校验
        if (dto.getEmail() == null || dto.getPassword() == null) {
            throw new ServiceException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        CloudUser selectOne = userMapper.selectOne(Wrappers.lambdaQuery(CloudUser.class).eq(CloudUser::getEmail, dto.getEmail()));
        // 验证用户是否存在
        if (selectOne == null) {
            throw new ServiceException(AppHttpCodeEnum.LOGIN_USER_NOT_EXIST);
        }

        String loginPass = DigestUtils.md5DigestAsHex((dto.getPassword() + selectOne.getSalt()).getBytes());
        // 验证密码是否正确
        if (!selectOne.getPassword().equals(loginPass)) {
            throw new ServiceException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 签发token
        return JwtUtil.generateToken(selectOne.getName(), String.valueOf(selectOne.getId()));
    }
}

